﻿using Paperless.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Paperless.Repositories
{
    public class TransactionRepository : BaseRepository<Transaction>
    {
        public override async System.Threading.Tasks.Task<int> Update(Transaction updatedEntity)
        {
            using(var context = Context)
            {
                var entity = await GetBy(updatedEntity.Id);

                if (entity.AssignAgents != null)
                {
                    foreach (var agent in entity.AssignAgents)
                    {
                        var attachedAgent =
                            context.Agents.Where(x =>
                                x.UserId == agent.UserId &&
                                x.TransactionId == updatedEntity.Id
                            ).FirstOrDefault();

                        if (attachedAgent != null)
                        {
                            context.Agents.Remove(attachedAgent);
                        }

                    }
                }

                foreach (var agent in updatedEntity.AssignAgents)
                {
                    agent.TransactionId = entity.Id;
                    context.Agents.Add(agent);
                }

                await context.SaveChangesAsync();
            }

            return await base.Update(updatedEntity);
        }
    }
}